package tcss543.auction;

import java.util.*;
import tcss543.*;

public class Auction {
	public AuctionResult doAuction(DeviceGraph graph, int[][] matching) {
		AuctionGraphBuilder builder = new AuctionGraphBuilder();
		AuctionGraph ag = builder.buildAuctionGraph(matching, graph);
		
		HashSet<Requestor> tmpRequestors = new HashSet<Requestor>();
		
		Requestor requestor;
		HelperGroup helperGroup;
		double currentBid = 0;
		double currentAsk = 0;
		
		while ((requestor = ag.requestors.pollLast()) != null) {
			helperGroup = ag.helperGroups.pollFirst();
			
			if (requestor.bidPrice >= helperGroup.askPrice) {
				if (ag.requestors.isEmpty()) {
					requestor.included = true;
					helperGroup.included = true;
					currentBid = requestor.bidPrice;
					currentAsk = helperGroup.askPrice;
					tmpRequestors.add(requestor);
				} else if (ag.requestors.getLast() != null
						&& ag.requestors.getLast().bidPrice >= ag.helperGroups.getFirst().askPrice) {
					requestor.included = true;
					helperGroup.included = true;
					currentBid = ag.requestors.getLast().bidPrice;
					currentAsk = ag.helperGroups.getFirst().askPrice;
					tmpRequestors.add(requestor);
				}
			} else {
				break;
			}
		}
		
		int[][] remainingMatches = new int[matching.length][];
		
		double profit = 0;
		
		for (Requestor r : tmpRequestors) {
			if (r.helperGroup.included) {
				remainingMatches[r.i] = r.helperGroup.helperIndices;
				profit += currentBid - currentAsk;
			}
		}
		
		return new AuctionResult(remainingMatches, currentBid, currentAsk, profit);
	}
}
